package com.superb.system.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.superb.common.core.annotation.SuperbRestMapping;
import com.superb.common.core.model.Result;
import com.superb.common.database.vo.BatchId;
import com.superb.common.database.vo.PageParams;
import com.superb.common.redis.key.KeyType;
import com.superb.common.redis.key.RedisKey;
import com.superb.common.redis.utils.RedisUtils;
import com.superb.common.utils.StringUtils;
import com.superb.system.api.entity.SystemUser;
import com.superb.system.service.SystemUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

/**
 * 系统用户表;(system_user)表控制层
 *
 * @Author: ajie
 * @CreateTime: 2024-5-7
 */
@Tag(name = "系统用户表接口")
@SuperbRestMapping("/systemUser")
@ApiSupport(author = "莫杰：ajie20999@163.com", order = 3)
public class SystemUserController {

    @Resource
    private SystemUserService systemUserService;

    @PostMapping("pageQuery")
    @ApiOperationSupport(order = 1)
    @Operation(summary = "分页查询", description = "权限预留<br>")
    public Result<Page<SystemUser>> pageQuery(@RequestBody PageParams<SystemUser> params) {
        SystemUser user = params.getParams();
        LambdaQueryWrapper<SystemUser> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotBlank(user.getNickname()), SystemUser::getNickname, user.getNickname())
                .eq(StringUtils.isNotBlank(user.getOrganId()), SystemUser::getOrganId, user.getOrganId())
                .like(StringUtils.isNotBlank(user.getPhoneNumber()), SystemUser::getPhoneNumber, user.getPhoneNumber());
        Page<SystemUser> result = systemUserService.page(params.getPage(), lqw);
        return Result.success(result);
    }

    @PostMapping("insert")
    @ApiOperationSupport(order = 2)
    @Operation(summary = "新增数据", description = "权限预留<br>")
    public Result<Boolean> insert(@RequestBody @Validated SystemUser systemUser) {
        if (systemUserService.checkUsername(systemUser.getUsername())) {
            return Result.error("当前登录名已重复！");
        }
        if (systemUserService.checkPhoneNumber(systemUser.getPhoneNumber())) {
            return Result.error("当前手机号已注册！");
        }
        if (systemUserService.checkEmail(systemUser.getEmail())) {
            return Result.error("当前手机号已注册！");
        }
        // 10位随机数，作为登录密码的秘钥
        String salt = RandomStringUtils.random(10, "SuperbAjiez01654+/=*");
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        systemUser.setPassword(encoder.encode(salt + "12345678"));
        systemUser.setSalt(salt);
        if (systemUserService.save(systemUser)) {
            return Result.success("用户新增成功！");
        }
        return Result.error("用户添加失败！");
    }

    @PostMapping("update")
    @ApiOperationSupport(order = 3)
    @Operation(summary = "根据id修改数据", description = "权限预留<br>")
    public Result<SystemUser> update(@RequestBody SystemUser systemUser) {
        systemUser.setPassword(null);
        systemUser.setSalt(null);
        if (systemUserService.updateById(systemUser)) {
            RedisKey key = new RedisKey(KeyType.PER, "userInfo:" + systemUser.getId());
            RedisKey key2 = new RedisKey(KeyType.TIME, "user:" + systemUser.getId());
            RedisKey key3 = new RedisKey(KeyType.TIME, "userCache:" + systemUser.getId());
            RedisUtils.build().hash().del(key, "info");
            RedisUtils.build().del(key2, key3);
            return Result.success();
        }
        return Result.error();
    }

    @GetMapping("delete/{id}")
    @ApiOperationSupport(order = 4)
    @Operation(summary = "根据id删除", description = "权限预留<br>")
    public Result<Boolean> deleteById(@PathVariable String id) {
        if (systemUserService.removeById(id)) {
            RedisKey key = new RedisKey(KeyType.PER, "userInfo:" + id);
            RedisKey key2 = new RedisKey(KeyType.TIME, "user:" + id);
            RedisUtils.build().hash().del(key, "info");
            RedisUtils.build().del(key2);
            return Result.success();
        }
        return Result.error();
    }

    @GetMapping("delQuery")
    @ApiOperationSupport(order = 5)
    @SaCheckPermission({"system:user:select", "system:user:delete"})
    @Operation(summary = "回收站", description = "权限: <br>同时拥有system:user:select、system:user:delete")
    public Result<List<SystemUser>> delQuery() {
        List<SystemUser> result = systemUserService.delPage();
        return Result.success(result);
    }

    @PostMapping("recovery")
    @ApiOperationSupport(order = 6)
    @SaCheckPermission({"system:user:update", "system:user:delete"})
    @Operation(summary = "根据id恢复删除的数据", description = "权限: <br>同时拥有system:user:update、system:user:delete")
    public Result<Boolean> recovery(@RequestBody @Validated BatchId batchId) {
        if (systemUserService.recoveryByBatchId(batchId.getId())) {
            return Result.success();
        }
        return Result.error();
    }

    @PostMapping("delete")
    @ApiOperationSupport(order = 7)
    @SaCheckPermission("system:user:delete")
    @Operation(summary = "根据id彻底删除", description = "权限: system:user:delete<br><font style='color: red'>真删除，数据无法恢复</font>")
    public Result<Boolean> delete(@RequestBody @Validated BatchId batchId) {
        if (systemUserService.deleteByBatchId(batchId.getId())) {
            return Result.success();
        }
        return Result.error();
    }

    @GetMapping("info/{id}")
    @ApiOperationSupport(order = 8)
    @Operation(summary = "根据id获取用户信息", parameters = {
            @Parameter(name = "id", description = "用户id", required = true, in = ParameterIn.PATH)
    })
    public Result<SystemUser> info(@PathVariable String id) {
        return Result.success(systemUserService.getInfoById(id));
    }

    @PostMapping("updatePassword")
    @ApiOperationSupport(order = 9)
    @SaCheckPermission({"system:user:update"})
    @Operation(summary = "根据id修改密码", description = "权限： system:user:update<br>")
    public Result<SystemUser> updatePassword(@RequestBody SystemUser systemUser) {
        // 10位随机数，作为登录密码的秘钥
        String salt = RandomStringUtils.random(10, "SuperbAjiez01654+/=*");
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        systemUser.setPassword(encoder.encode(salt + systemUser.getPassword()));
        systemUser.setSalt(salt);
        if (systemUserService.updateById(systemUser)) {
            return Result.success();
        }
        return Result.error();
    }
}